<?php //use_stylesheets_for_form($form) ?>
<?php //use_javascripts_for_form($form) ?>
<?PHP echo javascript_include_tag("voucher/voucher_new.js") ?>
<script type="text/javascript">

    $(document).ready(function() {
        var lb_1 = showLoadingBar()

        //availableSummaryTitle = [<?PHP //echo html_entity_decode($summary_title); ?>]
        availableSummaryTitle = []  //摘要
        //availableSubjectes = []   //会计科目
        subject_options = ""
        
        url_summaries = "<?PHP echo crossLinkApp::cross_app_link_to('api', '@api',array('module'=>'fin','action'=>'getVoucherSummaries', 'sf_format'=>'json')) ?>"
        url_subjectes = "<?PHP echo crossLinkApp::cross_app_link_to('api', '@api',array('module'=>'fin','action'=>'getAccountSubjectesOption', 'sf_format'=>'html')) ?>"
        //$.get(url_summaries,'',function(data){
        //  availableSummaryTitle = data
        //  enableVoucherSummaryAutoComplete(availableSummaryTitle)
        //  enableFormValidationEngine()
        //})

        //voucher date picker
        $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
        $("#voucher_date").datepicker({                       
			showOn: 'button',
			buttonImage: '/images/icons/calendar.png',
			buttonImageOnly: true,
                        dateFormat: 'yy-mm-dd',
                        minDate: '<?PHP echo date('Y-m-').'01' ?>'
        });
        //$("#voucher_date").datepicker($.datepicker.regional['fr']);

        //$('#voucher_date').datepicker('option', $.datepicker.regional['zh-CN']);

        //载入摘要
        $.ajax({
            url: url_summaries,
            type: "post",
            async: false,
            beforeSend: function(){
                lb_loadsummaries = showLoadingBar("正在载入摘要...")
            },
            success: function(data){
                availableSummaryTitle = data
                enableVoucherSummaryAutoComplete(availableSummaryTitle)
                //enableFormValidationEngine()
            },
            error: function(){
                showErrorDialog('载入摘要时发生错误,请刷新页面后重试.')
                showErrorBar('载入摘要时发生错误,请刷新页面后重试.')
            },
            complete: function(){
                hideLoadingBar(lb_loadsummaries)
            }
        })
        voucherelement_sn = 0   //初始化一个凭证项目的序号

        $.ajax({
            url: url_subjectes,
            type: "post",
            async: false,
            data: {"acct_set_id":<?PHP echo $current_set->getId(); ?>},
            beforeSend: function(){
                lb_loadsubjectes = showLoadingBar("正在载入会计科目...")
            },
            success: function(data) {
                //availableSubjectes = data
                subject_options = data
                //enableVoucherSubjectAutoComplete(availableSubjectes)
                //enableFormValidationEngine()
            },
            error: function(){
                showErrorDialog("载入会计科目时发生错误,请刷新页面后重试.")
                showErrorBar("载入会计科目时发生错误,请刷新页面后重试.")
            },
            complete: function() {
                hideLoadingBar(lb_loadsubjectes)
            }
        })

        $("#addVoucher").click(addVoucherElement)
        //初始时填入两笔记录
        for(var i = 0; i<2; i++) {
            addVoucherElement()
        }


        //激活表单校验
        enableFormValidationEngine()

        hideLoadingBar(lb_1)
        
        //$("#form_voucher").validationEngine({
            //如果form自身的检验成功,对表单整体进行效验
        //    success: function() {checkForm()},
        //    failure: function(){showErrorDialog("您的表单输入有错误,请修正后重试.")}
        //})
        
        //$("#btn_submit").button()
        //$("#btn_submit").click(clickButton)

        //$("#addVoucher").tinyTips('light','title')
        //$("addVoucher").simpletip({ showEffect: 'slide', hideEffect: 'slide', position: 'top', content: '请点击此处添加一行项目' });
        //$('input[id*=voucher_summary]').autocomplete({
        //    source: availableSummaryTitle,
        //    delay: 0,
        //    minLength:0
        //});

    });
</script>
<script type="text/javascript">
//以下函数定义全部转移到voucher_new.js文件中  2010-04-12
/*
    //更新debit 和credit的汇总栏位
    function refreshSummary() {

        var debit = getDebit()
        var credit = getCredit()
        var summary = summarizeDebitCredit(debit, credit)

        $("#debit_sum").html(summary[0])
        $("#credit_sum").html(summary[1])

    }
    
//function clickButton() {
//    alert('点击button了')
//}
     
    function addVoucherElement() {
        $("#tbody_voucher").append(generateVoucherElement())
        enableVoucherSummaryAutoComplete(availableSummaryTitle)
        enableDebitCreditSummary()
        //enableTooptip()
        $("#delete_element_" + voucherelement_sn).tinyTips('light', 'title')

    }

    function generateVoucherElement() {
        voucherelement_sn = voucherelement_sn + 1;  //init a serial sn
        var element_str = "<tr align='center' id='tr_element_" + voucherelement_sn + "'>"
        element_str += "<td><input type='text' id='voucher_summary_" + voucherelement_sn + "' name='voucher[][summary]' class='validate[length[2,100]]' /></td>"
        //element_str += "<td><input type='text' id='voucher_subject_" + voucherelement_sn + "' name='voucher[][subject]' class='validate[funcCall[validateDebitCredit]]'  /></td>"
        element_str += "<td><select style='width:320px;' id='voucher_subject_" + voucherelement_sn + "' name='voucher[][subject]' class='validate[funcCall[validateDebitCredit]]' ><option></option>" + subject_options + "</select></td>"
        element_str += "<td><input size='10' type='text' id='voucher_debit_" + voucherelement_sn + "' name='voucher[][debit]' class='validat[funcCall[validateDebitCredit],custom[validNumber]]' /></td>"
        element_str += "<td><input size='10' type='text' id='voucher_credit_" + voucherelement_sn + "' name='voucher[][credit]' class='validat[funcCall[validateDebitCredit],custom[validNumber]]' /></td>"
        element_str += "<td><img src='/images/icons/delete.png' onClick='deleteElement(\"tr_element_" + voucherelement_sn + "\")' id='delete_element_" + voucherelement_sn + "' title='点击此处删除该行'></td>"
        element_str += "</tr>"
        return element_str;

    }

    function validateDebitCredit() {
        var debit = getDebit()
        var credit = getCredit()
        //检查表单的借贷输入
        if(! validateDebitCreditInput(debit, credit) ) {
            return true
        }
        return false
    }

    //激活借贷栏位的汇总
    function enableDebitCreditSummary() {

        $("input[id*=voucher_debit]").change(function(){
            refreshSummary()
        })
        $("input[id*=voucher_credit]").change(function(){
            refreshSummary()
        })
    }

    function enableFormValidationEngine() {

        $("#form_voucher").validationEngine({
            //如果form自身的检验成功,对表单整体进行效验
            success: function() {checkForm()},
            //如果失败弹出错误对话框
            failure: function(){showErrorDialog("您的表单输入有错误,请修正后重试.")}
        })
    }

    //对表单进行全面检查。
    function checkForm() {

        var debit = getDebit()
        var credit = getCredit()
        var summary = getSummary()  //取摘要
        var subject = getSubject()  //取科目代码
        var error = 0
        var error_msg = ''

        //alert("现在对整表进行检查")
        //检查借贷栏目的填写
        if(! validateDebitCreditInput(debit, credit)){
            error += 1
            error_msg += "借贷金额填写有误，请修改正确后重试。<br />"
        }
        //检查借贷是否平衡
        if(! validateDebitCreditBalance(debit, credit)) {
            error += 1
            error_msg += "借贷金额总计不相同，请修改正确后重试。<br />"
        }

        //检查摘要栏位是否填写正确
        if(! validateVoucherFormInput(summary, subject, debit, credit) ){
            error += 1
            error_msg += "表单检验出错，请确认栏位填写正确。<br />"
        }
        //重新激活表单校验
        enableFormValidationEngine()

        if(error) {
            showErrorDialog(error_msg,"表单校验出错")
        } else {
            //校验成功,弹出确认对话框
            alert('校验成功,进行确认')
            showConfirmDialog('您确定要对填写的内容进行保存吗?','保存?', saveForm)
        }

    }

    function saveForm() {
        var debit = getDebit()
        var credit = getCredit()
        var summary = getSummary()
        var subject = getSubject()
        //将数组转成string $.JSON.encode(array). 将字串转成json: $.JSON.decode(str)
        var poststr = "{"
        poststr += "debit:" + $.JSON.encode(debit)
        poststr += ",credit:" + $.JSON.encode(credit)
        poststr += ",summary:" + $.JSON.encode(summary)
        poststr += ",subject:" + $.JSON.encode(subject)
        poststr += ",acct_set_id:<?PHP //echo $current_set->getId() ?>"
        poststr += "}"
        var postdata = $.JSON.decode(poststr) //将string转成json
        //通过ajax提交表单
        
        //$.ajax({

        //})
        
        alert('Now Saving Form')
    }
*/
</script>

<form id="form_voucher" action="<?PHP echo url_for("voucher/create") ?>">

    <fieldset id="voucher_fields">
        <legend>记账凭证</legend>
        <table>
            <thead>
                <tr>
                    <th colspan="4">
                        日期: <input type="text" readonly="readonly" name="voucher_date" id="voucher_date" maxlength="10"  size="10" value="<?PHP echo date("Y-m-d") ?>" />
                        
                    </th>
                </tr>
                <tr>
                    <th>摘要</th>
                    <th>科目代码与名称</th>
                    <!-- <th>科目代码</th> -->
                    <th>借方金额</th>
                    <th>贷方金额</th>
                    <th><a href="#" id="atooltip"><img id="addVoucher" src="/images/icons/add.png" alt="添加项目" title ="点击这里添加新行" /></a></th>
                </tr>
            </thead>
            <div class="ui-widget">

                <tbody id="tbody_voucher">
                    <!-- <tr>
                        <td><input type="text" id="voucher_summary_1" name="voucher[][summary]" /></td>
                        <td><input type="text" id="voucher_subject_1" name="voucher[][subject]" /></td>
                        <td><input size="10" type="text" id="voucher_debit_1" name="voucher[][debit]" /></td>
                        <td><input size="10" type="text" id="voucher_credit_1" name="voucher[][credit]" /></td>
                    </tr>
                    <tr>
                        <td><input type="text" id="voucher_summary_1" name="voucher[][summary]" /></td>
                        <td><input type="text" id="voucher_subject_1" name="voucher[][subject]" /></td>
                        <td><input size="10" type="text" id="voucher_debit_1" name="voucher[][debit]" /></td>
                        <td><input size="10" type="text" id="voucher_credit_1" name="voucher[][credit]" /></td>
                    </tr>
                    -->
                </tbody>
                <thead>
                    <tr>
                        <th>金额合计</th>
                        <th></th>
                        <th id="debit_sum">0.00</th>
                        <th id="credit_sum">0.00</th>
                        <th></th>
                    </tr>
                </thead>
            </div>
            <tfoot>
                <tr>
                    <td colspan="5" align="center">
                        <input type="hidden" name="acct_set_id" value="<?PHP echo $current_set->getId() ?>" />
                        <button type="submit" id="btn_submit">保存</button>
                    </td>
                </tr>
            </tfoot>

        </table>
    </fieldset>

</form>
